const App = getApp();
// 工具类
import Util from '../../../../utils/util.js';
Page({
  /**
   * 页面的初始数据
   */
  onShareAppMessage() {
    return {
      title: 'picker-view',
      path: 'page/component/pages/picker-view/picker-view'
    }
  },
  data: {
    freshen :true,
    isLogin: false,
    teamId:0,
    nid:0,
    detail:{},
    off_status:1,
    maoHao: '：',
    fileList: [],
    cateindex:0,
    dateList:{
              endDate: "",
              endTime: "",
              signEndDate: "",
              signEndTime: "",
              signStratDate: "",
              signStratTime: "",
              stratDate: "",
              stratTime: ""
            },//时间
    area:"",
    address:"",
    latitude:"", //纬度
    longitude:"",//经度
    theme: [],//主题标签
    themeValue:"",
    location:1, //权限：1代表处，2分队
    isLocation:false, //是否选择权限
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      nid:options.nid,
    })
    console.log(options)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    console.log("freshen=",this.data.freshen);
    if(this.data.freshen){
      let that = this;
      that.setData({
        isLogin: App.checkIsLogin(),
      });
      //10007分队管理，10008代表处管理，10009分队管理+代表处管理
      let user_info = wx.getStorageSync('user_info') //用户信息
      if (that.data.isLogin) {
        //获取服务队
        that.setData({
          teamId: App.checkTeam(),
          isLocation:user_info.grade_id == "10009"?true:false
        });
        that.getTheme()
        if(that.data.nid > 0){
          //详情
          that.getDetail();
        }

      }
    }
  },
  getTheme(){
    let _this = this;
    App._get('activity/theme', {}, result => {
      _this.setData({
          theme:result.data.data
        })
    });
  },
  /**
   * 详情
   */
  getDetail() {
    console.log("getDetail")
    let _this = this;
    let obj = {
      activity_id:this.data.nid
    }
    App._get('activity/detail', obj, result => {
      let themeValue=result.data.detail.theme_label
      let theme = [];
      if(themeValue){
        theme=themeValue.split(",")
      }
      _this.checkboxChange({detail:{value:theme}})
      const fileList = [];
      // // 将图片信息添加到fileList数字中
      fileList.push({
        file_id:result.data.detail.image.file_id,
        url:result.data.detail.image.file_path
      });
      let location = 2; //默认分队
      if(result.data.detail.team_id == 0){ //代表处
        location = 1;
      }
      _this.setData({
        detail: result.data.detail,
        area: result.data.detail.area,
        address: result.data.detail.address,
        longitude: result.data.detail.longitude,
        latitude: result.data.detail.latitude,
        off_status: result.data.detail.off_status,
        themeValue,
        fileList,
        location,
        dateList:{
          endDate: Util.dateFormat('YYYY-mm-dd',result.data.detail.end_time),
          endTime: Util.dateFormat('HH:MM',result.data.detail.end_time),
          signEndDate: Util.dateFormat('YYYY-mm-dd',result.data.detail.end_sign),
          signEndTime: Util.dateFormat('HH:MM',result.data.detail.end_sign),
          signStratDate: Util.dateFormat('YYYY-mm-dd',result.data.detail.start_sign),
          signStratTime: Util.dateFormat('HH:MM',result.data.detail.start_sign),
          stratDate: Util.dateFormat('YYYY-mm-dd',result.data.detail.start_time),
          stratTime: Util.dateFormat('HH:MM',result.data.detail.start_time)
        }
      })
    });
  },
  // //获取微信收货地址
  chooseLocation(){
    wx.chooseLocation({
      success: (res) => {
        if(res.address!='' && res.name!=''){
          this.setData({
            address:res.address,
            latitude:res.latitude,
            longitude:res.longitude,
            freshen:false
          })
        }
        return false
      },
    })
  },
   // 删除照片
  deleteClick(event) {
    var imgData = this.data.fileList;
    // 通过splice方法删除图片
    imgData.splice(event.detail.index, 1);
    // 更新图片数组
    this.setData({
        fileList: imgData
    })
    console.log(this.data.fileList)
  },

  // 图片上传
  afterRead(event) {
    let that = this;//防止this指向问题
    // loading加载
    wx.showLoading({title: '上传中...'});
    //获取图片详细信息
    const {file} = event.detail;
     //调用上传图片方法
     that.uploadCompressImg(file).then(res=>{
      App.uploadFile(res,{},function(result){
        const fileList = [];
        // // 将图片信息添加到fileList数字中
        fileList.push({
            url: result.data.file_path,
            file_id:result.data.file_id,
        });
        // 更新存放图片的数组
        that.setData({
            fileList
        });
         wx.hideLoading();//停止loading
      })
    })
  },
  
  //提交
  formSubmit(e) {
    console.log("themeValue",this.data.themeValue)
    var formData=e.detail.value;//获取表单数据
    let formStatus = false
    for (let key in formData) {
      if(formData[key] == ""){
        formStatus = true
        break;
      }
    }
    if(formStatus){
      App.showError("活动信息不全！");
      return;
    }
    let timestatus =false
    let dateList = this.data.dateList
    for (let key in dateList) {
      if(dateList[key] == ""){
        timestatus = true
        break;
      }
    }
   if(timestatus){
      App.showError("报名时间和活动时间不能空!");
      return;
    }
    if(!this.data.fileList.length){
      App.showError("封面图片不能空!");
      return;
    }
    
    let obj = {
      activity_id:this.data.nid,
      activity_title:formData.activity_title, //标题
      subtitle:formData.subtitle, //副标题
      contacts:formData.contacts, //负责人
      phone:formData.phone, //联系电话
      area:this.data.area, //联系地址（省市区）
      address:formData.address, //联系地址（详细）
      latitude:formData.latitude, //纬度
      longitude:formData.longitude, //经度
      off_status:this.data.off_status, //活动类型
      start_sign:dateList.signStratDate+" "+dateList.signStratTime,  //报名开始
      end_sign:dateList.signEndDate+" "+dateList.signEndTime,  //报名结束
      start_time:dateList.stratDate+" "+dateList.stratTime,  //活动开始
      end_time:dateList.endDate+" "+dateList.endTime,  //活动结束
      people_num:formData.people_num, //活动人数
      activity_money:formData.activity_money, //活动金额
      activity_content:formData.activity_content, //内容
      image_id:this.data.fileList[0].file_id, //图片ID
      theme_label:this.data.themeValue,
      location:this.data.location,//1代表处，2分队
      examine_status:0, //审核状态
    };
    console.log(obj);
    App._post_form('activity/release', obj, result => {
      //成功提示
      App.showSuccess(result.msg, function() {
        wx.navigateTo({
          url: "/pages/user/activity/index",
        })
      });
    });
  },

  //活动类型
  radioChange(e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)
    this.setData({
      off_status : e.detail.value,
    })
  },
    //活动类型
    locationChange(e) {
      console.log('radio发生change事件，携带value值为：', e.detail.value)
      this.setData({
        location:e.detail.value
      })
    },

  //选择日期
  bindDateChange: function (e) {
    let that = this;
    let type = e.currentTarget.dataset.type
    const List = that.data.dateList;
    List[type] = e.detail.value;
    that.setData({
      dateList:{
         ... List
      }
    });
    console.log("dateList",that.data.dateList)
  },

  //省市区
  bindRegionChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      area:e.detail.value[0]+" "+e.detail.value[1]+" "+e.detail.value[2]
    })
  },

  //图片压缩
  uploadCompressImg(file) {
    let that = this
    return new Promise(function(resolve, reject){
      let file_url = file.tempFilePath
      console.log(file);
      if(file.size < 500*1024){
        console.log("size",file.size)
        console.log("file_url",file_url)
        resolve(file_url);
      }else{
          // 获得原始图片大小
          wx.getImageInfo({
            src: file_url,
            success(res) {
              console.log(res);
            
              let originHeight = res.height;
              let originWidth = res.width;
              // 压缩比例
              // 最大尺寸限制
              let maxWidth = 1024,
                maxHeight = 1024;
              // 目标尺寸
              let targetWidth = originWidth,
                targetHeight = originHeight;
              // 等比例压缩，如果宽度大于高度，则宽度优先，否则高度优先
              if (originWidth > maxWidth || originHeight > maxHeight) {
                if (originWidth / originHeight > maxWidth / maxHeight) {
                  // 要求宽度*(原生图片比例)=新图片尺寸
                  targetWidth = maxWidth;
                  targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                } else {
                  targetHeight = maxHeight;
                  targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                }
              }
console.log('更新 canvas 大小')
              // 更新 canvas 大小
              that.setData({
                "cw": targetWidth,
                "ch": targetHeight
              });
              // 尝试压缩文件，创建 canvas
              let ctx = wx.createCanvasContext('canvas');
              ctx.clearRect(0, 0, targetWidth, targetHeight);
              //通过得到图片旋转的角度来调整显示方向以正确显示图片，主要解决 ios 系统上的图片会有旋转的问题
              let orientation = res.orientation;
              if (orientation == 'right') { //exif的6
                that.setData({
                  "cw": targetHeight,
                  "ch": targetWidth
                });
                ctx.rotate(90 * Math.PI / 180);
                ctx.drawImage(file_url, 0, 0, targetWidth, targetHeight, 0, -targetHeight, that.data.ch, that.data.cw);
              } else {
                ctx.drawImage(file_url, 0, 0, targetWidth, targetHeight);
              }

              ctx.draw(false, function () {
                // 获得新图片输出
                wx.canvasToTempFilePath({
                  x: 0,
                  y: 0,
                  canvasId: 'canvas',
                  destWidth: targetWidth,
                  destHeight: targetHeight,
                  quality: 0.9,
                  fileType: "jpg",
                  success: (res) => {
                    console.log(res)
                    resolve(res.tempFilePath);
                  },
                  fail: (err) => {
                    console.error(err)
                  }
                }, this)
              })
            }
          })
      }
    })
  },
  //主题标签选择
  checkboxChange(e) {
    console.log('checkbox发生change事件，携带value值为：', e.detail.value)
    const theme = this.data.theme
    const values = e.detail.value
    for (let i = 0, lenI = theme.length; i < lenI; ++i) {
      theme[i].checked = false
      for (let j = 0, lenJ = values.length; j < lenJ; ++j) {
        if (theme[i].value === values[j]) {
          theme[i].checked = true
          break
        }
      }
    }
    this.setData({
      theme,
      themeValue:values.join()
    })
  },

})